package com.springlearn.zhoufei.other.spring.demo5;

/**
 * 描述该类- JPA
 *
 * @author zhoufei
 * @class: StudentJDBCTemplate
 * @date 2020/10/3  9:54
 * @Verson 1.0 -2020/10/3  9:54
 * @see
 */

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcCall;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

public class StudentJDBCTemplate implements StudentDAO {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplateObject;
    
    @Override
    // 设置数据源
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
    }
    
    @Override
    public void insert(String name, Integer age) {
        
        String SQL = "insert into Student (name, age) values (?, ?)";
        jdbcTemplateObject.update(SQL, name, age);
        return;
    }
    
    @Override
    public Student getById(Integer id) {
        
        String SQL = "select * from Student where id = ?";
        Student student = jdbcTemplateObject.queryForObject(SQL, new Object[] { id }, new StudentMapper());
        return student;
    }
    
    @Override
    public List<Student> list() {
        
        String SQL = "select * from Student";
        List<Student> students = jdbcTemplateObject.query(SQL, new StudentMapper());
        return students;
    }
    
    @Override
    public void delete(Integer id) {
        
        String SQL = "delete from Student where id = ?";
        jdbcTemplateObject.update(SQL, id);
        return;
    }
    
    @Override
    public void update(Integer id, Integer age) {
        
        String SQL = "update Student set age = ? where id = ?";
        jdbcTemplateObject.update(SQL, age, id);
        return;
    }
    
    @Override
    // 存储过程
    public Student procedure01(Integer id) {
        SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id);
        
        SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("getRecordById");
        
        Map<String, Object> out = jdbcCall.execute(in);
        Student student = new Student();
        student.setId(id);
        student.setName((String) out.get("out_name"));
        student.setAge((Integer) out.get("out_age"));
        return student;
        
    }
}